<template>
  <a-modal v-model:visible="visible" :title="modalTitle" width="35%" @ok="handleOk" @cancel="handleCancel">
    <a-form :model="formState" ref="formRef" :label-col="{ span: 5 }">
      <a-form-item label="物流公司" name="name" :rules="[{ required: true, message: '请输入物流公司' }]">
        <a-input placeholder="请输入物流公司" v-model:value="formState.name" />
      </a-form-item>
      <a-form-item label="物流编码" name="code" :rules="[{ required: true, message: '请输入物流编码' }]">
        <a-input placeholder="请输入物流编码" v-model:value="formState.code" />
      </a-form-item>
      <a-form-item label="图标" name="img">
        <a-form-item-rest>
          <app-upload :fileList="formState.img" :min="1" @upload-img="uploadImg" />
        </a-form-item-rest>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>
import useModal from "@/utils/useModal";
import { message } from "ant-design-vue";
import { reactive } from "vue";
import { edit, add, info } from "@/api/systemShip";

import { ref } from "vue";
const { visible, modalTitle } = useModal();
const emits = defineEmits(["modal-success"]);

const formState = reactive({
  name: "",
  code: "",
  img: [],
});
const formRef = ref();

const show = (model) => {
  visible.value = true;
  modalTitle.value = model ? "编辑物流公司" : "新增物流公司";
  if (model && model.ship_id) {
    getDetails(model.ship_id);
  } else {
    resetForm({
      ship_id: null,
      name: "",
      code: "",
      img: [],
    });
  }
};
const getDetails = (id) => {
  info({
    id: id,
  }).then((res) => {
    if (res.code === 0) {
      const data = res.data;
      resetForm(data);
      formState.img = formState.img
        ? [
          {
            url: formState.img,
          },
        ]
        : [];
    }
  });
};
const handleOk = async () => {
  await formRef.value.validate().then(() => {
    let params = {
      ...formState,
      img: formState.img.length > 0 ? formState.img[0]?.url : "",
    };
    if (formState.ship_id) {
      edit({
        id: formState.ship_id,
        ...params,
      }).then((res) => {
        if (res.code == 0) {
          message.success(res.msg);
          formRef.value.resetFields();
          visible.value = false;
          emits("modal-success");
        }
      });
    } else {
      add(params).then((res) => {
        if (res.code == 0) {
          message.success(res.msg);
          formRef.value.resetFields();
          visible.value = false;
          emits("modal-success");
        }
      });
    }
  });
};
//设置表单的值
const resetForm = function (values) {
  for (var i in values) {
    formState[i] = values[i];
  }
};
const uploadImg = (val) => {
  formState.img = formState.img.concat(val);
};
const handleCancel = (e) => {
  formRef.value.resetFields();
};
// 暴露方法
defineExpose({
  show,
});
</script>
  